package cn.wolfcode.luowowo.itemshop.service.impl;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.common.customexception.UserInfoException;
import cn.wolfcode.luowowo.itemshop.domain.ItemShopProp;
import cn.wolfcode.luowowo.itemshop.domain.UserProp;
import cn.wolfcode.luowowo.itemshop.mapper.ItemShopPropMapper;
import cn.wolfcode.luowowo.itemshop.mapper.UserPropMapper;
import cn.wolfcode.luowowo.itemshop.qo.ShopPropQueryObject;
import cn.wolfcode.luowowo.itemshop.service.IUserPropService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

@Service
public class UserPropServiceImpl implements IUserPropService {

    @Autowired
    private UserPropMapper userPropMapper;

    @Autowired
    private ItemShopPropMapper itemShopPropMapper;

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Reference
    private IUserInfoService userInfoService;

    @Override
    public PageInfo queryByUserId(ShopPropQueryObject qo) {

        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        return new PageInfo(userPropMapper.selectForList(qo));
    }


    @Override
    public void buy(UserInfo userInfo, ItemShopProp itemShopProp, String token) {

        //判断此次道具库从是否充足
        if(itemShopProp  == null || itemShopProp.getRest() <=0 ){

            throw new UserInfoException("没有此道具或库存不足");

        }

        //判断用户金币是否充足
        if(userInfo.getScore().compareTo(itemShopProp.getPrice()) == -1){
            throw new UserInfoException("金币余额不足");
        }

        //进行购买操作
        userInfo.setScore(userInfo.getScore().subtract(itemShopProp.getPrice()));

        userInfoService.updateScore(userInfo.getId(),userInfo.getScore());


        //库存减少
        itemShopProp.setRest(itemShopProp.getRest() - 1);

        itemShopPropMapper.updateByPrimaryKey(itemShopProp);

        //用户道具数量增加
        UserProp userProp = userPropMapper.queryByName(itemShopProp.getName());

        if(userProp == null){

            userPropMapper.insert(new UserProp(userInfo.getId(),itemShopProp.getImgUrl(),itemShopProp.getName()
            ,1,new Date(),""));

        }else{

            userProp.setRest(userProp.getRest() + 1);

            userPropMapper.updateByPrimaryKey(userProp);
        }

        //改变Redis中存放的用户信息
        userInfoRedisService.setLoginUserInfo(token, JSON.toJSONString(userInfo));
    }
}
